import axios from 'axios'
import { Message } from 'element-ui'
import stoer from '@/store'
import router from '@/router'
import store from '@/store'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(res => {
  if (stoer.getters.token) {
    const TiemTokne = localStorage.getItem('TiemTokne')
    const now = Date.now()
    const timeout = 999999999999
    if (now - TiemTokne >= timeout) {
      // localStorage.removeItem('token')
      // localStorage.removeItem('TiemTokne')
      store.dispatch('user/logout')
      router.push('/login')
      return Promise.reject(new Error('登录超时'))
    } else {
      res.headers.Authorization = `Bearer ${stoer.getters.token}`
    }
  }
  return res
}, err => {
  Promise.reject(new Error('登录超时'))
  return err
})

// response interceptor
service.interceptors.response.use(res => {
  const { success, data, message } = res.data
  if (success) {
    console.log('数据成功')
    return data
  } else {
    console.log('数据失败')
    Message.error(message)
    return Promise.reject(new Error(message))
  }
}, err => {
  if (err.response && err.response.data.code === 10002) {
    store.dispatch('user/logout')
    router.push('/login')
    Message.error(err.response.data.message)
  }
  return Promise.reject(new Error(err.message))
})

export default service
